package com.yhzl.two.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yhzl.two.shop.common.ServerResponse;
import com.yhzl.two.shop.common.ServiceCommonMethod;
import com.yhzl.two.shop.entity.Address;
import com.yhzl.two.shop.mapper.AddressMapper;
import com.yhzl.two.shop.service.IAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chsm
 * @since 2018-09-04
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {

    @Override
    public ServerResponse<String> add(Address address) {
        // 更新默认地址
        updateDefaultAddress(address);
        int count = baseMapper.insert(address);
        return ServiceCommonMethod.returnInsert(count, "添加地址成功", "添加地址失败");
    }

    @Override
    public ServerResponse<String> delete(Integer id) {
        int count = baseMapper.deleteById(id);
        return ServiceCommonMethod.returnInsert(count, "删除地址成功", "删除地址失败");
    }

    @Override
    public ServerResponse<String> update(Address address) {
        // 更新默认地址
        updateDefaultAddress(address);
        int count = baseMapper.updateById(address);
        return ServiceCommonMethod.returnInsert(count, "更新地址成功", "更新地址失败");
    }

    @Override
    public ServerResponse<List<Address>> queryAll(Integer uid) {
        List<Address> addressList = baseMapper.selectList(new QueryWrapper<Address>()
                .eq("uid", uid));
        return ServerResponse.createSuccessData("获取地址信息成功", addressList);
    }

    /**
     * 更新默认地址
     * @param address   地址信息
     */
    private void updateDefaultAddress(Address address) {
        // 当前地址为默认地址时则更新
        if (address.getADefault()) {
            // 将原来默认地址取消
            baseMapper.update(
                    new Address().setADefault(false),
                    new UpdateWrapper<Address>()
                            .eq("uid", address.getUid())
                            .eq("is_default", true));
        }
    }
}
